package com.web.news.servlet;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.web.news.service.impl.NewsServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.web.news.pojo.Comments;
import com.web.news.pojo.News;
import com.web.news.pojo.NewsDo;
import com.web.news.pojo.Topic;
import com.web.news.service.NewsService;





public class AdminServlet extends HttpServlet {
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
		request.setCharacterEncoding("UTF-8");
		
		String action = request.getParameter("action");
		if("doNewsAdd".equals(action)) {
			doNewsAdd(request,response);
		}else if("toNewsAdd".equals(action)) {
			toNewsAdd(request,response);
		}else if ("adminIndex".equals(action)) {
			doAdminQuery(request,response);
		}else if ("updateIndex".equals(action)) {
			updateIndex(request,response);
		}else if ("doUpdateSubmit".equals(action)) {
			doUpdateSubmit(request,response);
			}else if ("deleteall".equals(action)) {
				deleteall(request,response);
			}
	}
	private void deleteall(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		int	nid = Integer.parseInt(request.getParameter("nid"));
		NewsService newsService = new NewsServiceImpl();
		newsService.deleteNews(nid);
		newsService.deleteComments(nid);
		response.sendRedirect(request.getContextPath()+"/AdminServlet?action=adminIndex");
	}
	
	private void updateIndex(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		int	nid = Integer.parseInt(request.getParameter("nid"));
		NewsService newsService = new NewsServiceImpl();
		List<Topic> topicList = newsService. findAllTopic();
		NewsDo newsDo = newsService.findNewDetailById(nid);
		List<Comments> commentList =  newsService.findCommentsByNews(nid);
		request.setAttribute("topicList", topicList);
		request.setAttribute("newsDetail", newsDo);
		request.setAttribute("commentList", commentList);
		
		
		request.getRequestDispatcher("newspages/news_modify.jsp").forward(request, response);
	}
	private void doAdminQuery(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		NewsService newsService = new NewsServiceImpl();
		int pageNum = 1;
		if(request.getParameter("pageNum")!=null){
			pageNum = Integer.parseInt(request.getParameter("pageNum"));
		}
		int pageSize = 15;
		PageHelper.startPage(pageNum,pageSize);
		List<News> list = newsService.findAllNews();
		//List<Topic> list1 = newsService.findAllTopic();
		PageInfo page = new PageInfo<>(list);
		
		//System.out.println(list1);
		request.setAttribute("newsList", list);
		//request.setAttribute("list1", list1);
		request.setAttribute("page", page);
		
		request.getRequestDispatcher("newspages/admin.jsp").forward(request, response);
		//response.sendRedirect(request.getContextPath() + "/newspages/admin.jsp");
	}

	private void toNewsAdd(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		NewsService newsService = new NewsServiceImpl();
		List<Topic> topicList = newsService.findAllTopic();
		request.setAttribute("topicList", topicList);
		request.getRequestDispatcher("newspages/news_add.jsp").forward(request, response);
	}

	private void doNewsAdd(HttpServletRequest request, HttpServletResponse response) throws IOException {
		
	try {
		
		DiskFileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		
		upload.setHeaderEncoding("UTF-8");
		upload.setFileSizeMax(1024*1024*3);
		
		List list = upload.parseRequest(request);
		News news = new News();
		Iterator it = list.iterator();
		while(it.hasNext()) {
			FileItem item = (FileItem)it.next();
			if(item.isFormField()) {
				String value = item.getString("UTF-8");
				
				if (item.getFieldName().equals("ntid")) {
					news.setNtid(Integer.parseInt(value));
				} else if(item.getFieldName().equals("ntitle")) {
					news.setNtitle(value);
				} else if(item.getFieldName().equals("nauthor")) {
					news.setNauthor(value);
				} else if(item.getFieldName().equals("nsummary")) {
					news.setNsummary(value);
				} else if(item.getFieldName().equals("ncontent")) {
					news.setNcontent(value);
				}
			}else {
				//D:\\apache-tomcat-8.0.50\\webapps\\MyNewsManager\\upload
				String path = request.getServletContext().getRealPath("upload");
				//System.out.println(path);
				
				File targetFile = new File(path, item.getName());
				item.write(targetFile );  
				news.setNpicpath(item.getName());
				
			}
		}
		NewsService newsService = new NewsServiceImpl();
		news.setNcreatedate(new Date());
		newsService.addNews(news);
	}catch (Exception e) {
		e.printStackTrace(); 
	}finally {
		response.sendRedirect(request.getContextPath()+"AdminServlet?action=adminIndex&pageNum=1");
	}
		
	}
	
	private void doUpdateSubmit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			DiskFileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload upload = new ServletFileUpload(factory);
			//设置文件上传的参数
			upload.setHeaderEncoding("UTF-8");
			//设置上传文件的最大容量
			upload.setFileSizeMax(1024*1024*3);
			
			List list = upload.parseRequest(request);
			//创建保存数据库的News对象
			News news = new News();
			Iterator it = list.iterator();
			while(it.hasNext()) {
				FileItem item = (FileItem) it.next();//表示表单中的每一个元素的对象 （文本或文件）
				
				if (item.isFormField()) { //判断当前FileItem的类别 ： 1. form的普通输入框   2. file文件域 
					// request.getParameter("nid");这种 已经失效
					String value = item.getString("UTF-8");
					
					if (item.getFieldName().equals("ntid")) {
						news.setNtid(Integer.parseInt(value));
					}else if(item.getFieldName().equals("nid")){
						news.setNid(Integer.parseInt(value));
					}else if(item.getFieldName().equals("ntitle")) {
						news.setNtitle(value);
					} else if(item.getFieldName().equals("nauthor")) {
						news.setNauthor(value);
					} else if(item.getFieldName().equals("nsummary")) {
						news.setNsummary(value);
					} else if(item.getFieldName().equals("ncontent")) {
						news.setNcontent(value);
					} else if(item.getFieldName().equals("npicpath")) {
						news.setNpicpath(value);
					}
				} else {
					//判断是否有文件重新上传
					if (!"".equals(item.getName())) {
						String path = request.getServletContext().getRealPath("upload");
						//System.out.println(path);
						
						//删除原来的图片
						String oldFileName = news.getNpicpath();
						if (oldFileName != null) {
							File oldFile = new File(path, news.getNpicpath());
							if (oldFile.exists()) {
								oldFile.delete();
							}
						}
						
						File targetFile = new File(path, item.getName());
						item.write(targetFile );  // 把item的二进制的文件数据另存到一个目标文件中。
						news.setNpicpath(item.getName());
						
						System.out.println("上传完成");
					}

				}
			}
			
			//保存数据库
			NewsService newsService = new NewsServiceImpl();
			news.setNcreatedate(new Date());
		newsService.saveNews(news);
		}catch (Exception e) {
			e.printStackTrace(); 
		}
			response.sendRedirect(request.getContextPath()+"AdminServlet?action=adminIndex");
		}


}
